import { useRoutes, useNavigate, useLocation } from "react-router-dom"
import { useEffect, useMemo } from "react"
import { useSelector, useDispatch } from "react-redux"
import { getInfo } from "@/store/actions"
import { generateRoutes } from "@/store/permission"

import { constantRoutes, asyncRoutes } from "@/pages/index"

// 白名单
const whiteList = ['/login']

function Page() {
    const dispatch = useDispatch();
    const { token, roles, accessRoutes } = useSelector(state => state.user)
    const navigator = useNavigate();
    const { pathname } = useLocation();

    // 监听token变化
    useEffect(() => {
        // 当token从无到有，有了token，才能获取用户信息
        if (token) {
            dispatch(getInfo())
        } else {
            navigator("/login", { replace: true })
        }

    }, [token])

    useEffect(() => {
        if (roles && roles.length > 0) {
            // roles中有角色，配合路由表和算法，生成当前用户可以访问的路由规则们
            // ....
            dispatch(generateRoutes(asyncRoutes, roles))
        }
    }, [roles])

    useEffect(() => {
        if (accessRoutes && accessRoutes.length > 0) {
            navigator("/dashboard", { replace: true })
        }
    }, [accessRoutes])

    useEffect(() => {
        // !whiteList.includes(pathname) 表示访问的路径并没有在白名单中
        // 如果在白名单中，是不需要token
        if (!whiteList.includes(pathname) && !token) {
            navigator("/login", { replace: true })
        }
        // 表示已经登录了，已经有token了，又访问登录页面
        if (token && pathname === "/login") {
            navigator("/", { replace: true })
        }
        if (token && pathname === "/") {
            navigator("/dashboard", { replace: true })
        }
    }, [pathname])

    // 计算出全部的路由规则
    const routes = useMemo(() => {
        const result = [...constantRoutes];  // 静态路由规则copy一份
        result[0].children = accessRoutes
        return result;
    }, [accessRoutes])

    const element = useRoutes(constantRoutes)
    return element;
}

export default Page;